import {
    CART_LIST,
    CHECK_ALL,
    UN_CHECK_ALL,
    CHECK_ITEM
} from "./mutations-type";

export default {
    state: {
        list: [],    //购物车的数据
        selectList: []  // 选中的数据
    },
    getters: {
        isCheckedAll(state) {
            return state.list.length == state.selectList.length;
        },
        total(state) {
            let total = {
                num: 0,
                price: 0
            }
            state.list.forEach(v => {
                if (v.checked) {
                    total.num += v.g_num;
                    total.price += (v.g_price * v.g_num) * 100
                }
            })
            return total;
        }
    },
    mutations: {
        [CART_LIST](state, cartArr) {
            state.list = cartArr;
             
            state.selectList = state.list.map(v=>{
                return v.id;
            })
        },

        // 全选
        [CHECK_ALL](state) {
            state.selectList = state.list.map(v => {
                v.checked = true
                return v.id;
            });
        },


        // 反选
        [UN_CHECK_ALL](state) {
            state.list.forEach(v => {
                v.checked = false;
            });
            state.selectList = [];
        },

        // 单选
        [CHECK_ITEM](state, index) {
            // console.log(index);
            let id = state.list[index].id;
            let i = state.selectList.indexOf(id);
            if (i > -1) {
                return state.selectList.splice(i, 1);
            } else {
                state.selectList.push(id);
            }
        }

    },
    actions: {
        checkAllFn({ commit, getters }) {
            getters.isCheckedAll ? commit('unCheckAll') : commit('checkAll')
        }
    }
}